package com.zhang.security;

import cn.hutool.core.util.StrUtil;
import com.zhang.entity.SysUser;
import com.zhang.service.SysUserService;
import com.zhang.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//jwt认证过滤器，SpringSecurity流程中的BasicAuthenticationFilter
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    UserDetailServiceImpl userDetailService;
    @Autowired
    SysUserService sysUserService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        if(request.getRequestURI().equals("/captcha")){     //请求为获取验证码时不进行jwt解析
            chain.doFilter(request,response);
            return;
        }


        String jwt = request.getHeader(jwtUtil.getHeader());    //获取jwt

        if(StrUtil.isBlankOrUndefined(jwt)){    //jwt为空则直接往后面走，相当于匿名访问
            chain.doFilter(request,response);
            return;
        }

        Claims claims = jwtUtil.getClaimByToken(jwt);   //jwt不为空则进行解析
        if(claims == null){
            throw new JwtException("token 异常");
        }
        if(jwtUtil.tokenIsExpired(claims)){
            throw new JwtException("token已过期");
        }

        String username = claims.getSubject();
        SysUser user = sysUserService.getByUsername(username);

        UsernamePasswordAuthenticationToken token =     //生成springsecurity的token并保存
                new UsernamePasswordAuthenticationToken(username,null,userDetailService.getUserAuthority(user.getId()));
        SecurityContextHolder.getContext().setAuthentication(token);

        request.setAttribute("username",username);  //方便GuestFilter中判断是否为guest用户，限制一些权限

        chain.doFilter(request,response);
    }
}
